package com.karaoke.android.player;

import android.databinding.adapters.ListenerUtil;
import android.databinding.adapters.ViewBindingAdapter;
import android.view.View;

/**
 * Created by allen on 2017/4/27.
 */

public class BindingAdapter {
    @android.databinding.BindingAdapter({"android:onViewDetachedFromWindow", "android:onViewAttachedToWindow"})
    public static void setListener(View view, final ViewBindingAdapter.OnViewDetachedFromWindow detach,
                                   final ViewBindingAdapter.OnViewAttachedToWindow attach) {
        final View.OnAttachStateChangeListener newListener;
        if (detach == null && attach == null) {
            newListener = null;
        } else {
            newListener = new View.OnAttachStateChangeListener() {
                @Override
                public void onViewAttachedToWindow(View v) {
                    if (attach != null) {
                        attach.onViewAttachedToWindow(v);
                    }
                }

                @Override
                public void onViewDetachedFromWindow(View v) {
                    if (detach != null) {
                        detach.onViewDetachedFromWindow(v);
                    }
                }
            };
        }
        final View.OnAttachStateChangeListener oldListener = ListenerUtil.trackListener(view,
                newListener, R.id.onAttachStateChangeListener);
        if (oldListener != null) {
            view.removeOnAttachStateChangeListener(oldListener);
        }
        if (newListener != null) {
            view.addOnAttachStateChangeListener(newListener);
        }
    }
}
